package com.mapbased.wfw.ws;

import java.io.*;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: mapbased.com</p>
 *
 * @author chy_hs(Baily)
 * @version 1.0
 */
public class FormUrlEncoder
{
    StringBuffer sb=new StringBuffer();
    public void addParam(String key,Object value)
    {
        if(value == null)
        {
            value="";
        }
        if(key == null)
        {
            return;
        }
        sb.append(encode(key)).append("=").append(encode(String.valueOf(value)));
    }

    static private String encode(String s)
    {
        try
        {
            return java.net.URLEncoder.encode(s,"utf-8");
        }
        catch(UnsupportedEncodingException ex)
        {
            throw new java.lang.RuntimeException(ex);
        }
    }

    public void addParams(java.util.HashMap m)
    {
        for(java.util.Iterator i=m.entrySet().iterator();i.hasNext();)
        {
            java.util.Map.Entry e=(java.util.Map.Entry)i.next();
            Object o=e.getValue();
            if(o instanceof String[])
            {
                String[] os=(String[])o;
                String s=os.length > 0 ? os[0] : "";
                this.addParam(String.valueOf(e.getKey()),s);

            }
            else
            {
                this.addParam(String.valueOf(e.getKey()),e.getValue());
            }

        }

    }

    public void reset()
    {
        this.sb.setLength(0);
    }

    public String toString()
    {
        return sb.toString();
    }

}
